package u1;

import gnu.trove.TIntHashSet;
import gnu.trove.decorator.TIntHashSetDecorator;

import java.io.PrintStream;
import java.util.Collection;
import java.util.Map;

/**
 * Write out an adjacency list in the following simple textual format:
 * 
 * <pre>
 * key 4 value value value value
 * key 2 value value
 * key 1 value
 * </pre>
 * 
 * where all sources and targets are non-negative integers, and the key is
 * followed by the (non-negative) number of targets.
 */
public class AdjWriter {
  private PrintStream os;
  private int pageCount, linkCount;

  public AdjWriter(PrintStream os) {
    this.os = os;
    pageCount = 0;
    linkCount = 0;
  }

  public void writeT(Map<Integer, TIntHashSet> adj) {
    for (Map.Entry<Integer, TIntHashSet> e : adj.entrySet())
      write(e.getKey(), new TIntHashSetDecorator(e.getValue()));
  }

  public <T extends Collection<Integer>> void write(Map<Integer, T> adj) {
    for (Map.Entry<Integer, T> e : adj.entrySet())
      write(e.getKey(), e.getValue());
  }

  public void write(Integer source, Collection<Integer> targets) {
    os.print(source);
    os.print(" ");
    os.print(targets.size());
    os.print(" ");
    for (Integer t : targets) {
      os.print(t);
      os.print(" ");
    }
    os.println();
    
    linkCount += targets.size();
    pageCount += 1;
  }
  
  /**
   * Number of pages written so far.
   *
   * @return non-negative
   */
  public int getPageCount() {
    return pageCount;
  }

  /**
   * Number of links written so far.
   * 
   * @return non-negative
   */
  public int getLinkCount() {
    return linkCount;
  }

  /**
   * Call this to close the stream (if it needs to be closed; System.out does
   * not need to be closed).
   */
  public void close() {
    os.close();
  }
}
/*
* Copyright (c) 2009 John Lees-Miller
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

